package com.wxxymakers.grademark.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxxymakers.grademark.exception.ServiceException;
import com.wxxymakers.grademark.model.entity.WxUser;
import com.wxxymakers.grademark.model.mapper.WxUserMapper;
import com.wxxymakers.grademark.utils.NumUtils;
import com.wxxymakers.grademark.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/12/21 13:39
 * @DESCRIBE
 */
@Slf4j
@Service
public class WxUserService {

    @Autowired
    private WxUserMapper userMapper;

    /**
     * 验证用户密码是否正确
     * @param user 包含明文用户名和密码
     * @return 成功与否
     */
    public boolean login(WxUser user) {
        WxUser wxUser = byUsername(user.getUsername());
        if (wxUser != null) {
            return wxUser.getPassword().equals(toHex(user.getUsername(), user.getPassword()));
        }
        return false;
    }

    @Transactional
    public boolean register(WxUser user) {
        if (user.getWtime() == null) user.setWtime(new Date());
        user.setNtime(new Date());
        user.setUsername(user.getJobNum());

        String username = user.getUsername();
        WxUser wxUser = byUsername(username);
        if (wxUser != null) {
            throw new ServiceException("该工号已注册！请直接登录！");
        }

        if (byTel(user.getTel()) != null) {
            throw new ServiceException("电话已被使用！");
        }

        if (byEmail(user.getEmail()) != null) {
            throw new ServiceException("邮箱已被使用！");
        }

        user.setPassword(toHex(user.getUsername(), user.getPassword()));

        if (user.getRoleId() == null || user.getRoleId() <= 0) user.setRoleId(1); // 设置一个默认角色

        return userMapper.insert(user) > 0;
    }

//    ///////// 需要在添加
    @Transactional
    public boolean delete(int uid) {
        return userMapper.deleteById(uid) > 0;
    }

    @Transactional
    public boolean change(WxUser user) {
        if (NumUtils.gtZero(user.getId())) {
            if (!StringUtils.isEmpty(user.getPassword())) { // 修改密码
                String username = user.getUsername();
                if (StringUtils.isEmpty(username)) {
                    WxUser wxUser = userMapper.selectById(user.getId());
                    username = wxUser.getUsername();
                }
                user.setPassword(toHex(username, user.getPassword()));
            }
            /*if (NumUtils.gtZero(user.getDutyId()) || NumUtils.gtZero(user.getDutyLevel())) { // 调整职位 修改任职时间
                user.setNDatetime(new Date());
            }*/
            return userMapper.updateById(user) > 0;
        }
        return false;
    }

    public WxUser byIdNo(int uid) {
        return userMapper.byIdNoJoin(uid);
    }

    public WxUser byId(int uid) {
        return userMapper.selectById(uid);
    }

    public WxUser byUsername(String username) {
        WxUser query = new WxUser();
        query.setUsername(username);
        return userMapper.selectOne(new QueryWrapper<>(query));
    }

    public WxUser byTel(String tel) {
        WxUser query = new WxUser();
        query.setTel(tel);
        return userMapper.selectOne(new QueryWrapper<>(query));
    }

    public WxUser byEmail(String email) {
        WxUser query = new WxUser();
        query.setEmail(email);
        return userMapper.selectOne(new QueryWrapper<>(query));
    }

    public WxUser byUsernameJoin(String username) {
        return userMapper.selectByNameJoin(username);
    }

    /**
     * 多条件分页查询
     * @param query 动态条件
     * @param joinInfo 是否加入关联信息 废弃
     * @param noSelf 是否不查询自己
//     * @param selfRole 当前登录用户的角色 当存在时 获取的用户角色是比它低的
     */
    public Page<WxUser> page(int page, int limit, WxUser query, @Deprecated boolean joinInfo, boolean noSelf) {
        QueryWrapper<WxUser> wrapper = new QueryWrapper<>(query);
        wrapper.orderByDesc("id");
        if (noSelf) {
            String username = (String) SecurityUtils.getSubject().getPrincipal();
            wrapper.ne("username", username);
        }

        int total = userMapper.selectCount(wrapper);
        if (total > 0) {
            List<WxUser> users = userMapper.selectPage(PageUtils.rowBounds(page, limit), wrapper).getRecords();
            return PageUtils.page(users, page, limit, total);
        }
        return null;
    }

    /*
     * 动态的构建查询条件
     * 1、用户名模糊查询  2、性别查询
     * 3、分部门查询      4、分职称查询
     * 5、按职称等级查询  6、职工号查询
     * 7、按用户角色查询  7、用户名查询
     * @param user 条件信息
     */
    /*private WxUserExample example(WxUser user) {
        WxUserExample example = new WxUserExample();
        WxUserExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(user.getName())) criteria.andNameLike("%" + user.getName() + "%");
        if (!StringUtils.isEmpty(user.getSex())) criteria.andSexEqualTo(user.getSex());
        if (!StringUtils.isEmpty(user.getJobNum())) criteria.andJobNumEqualTo(user.getJobNum());
        if (!StringUtils.isEmpty(user.getUsername())) criteria.andUsernameEqualTo(user.getUsername());
        if (!StringUtils.isEmpty(user.getEmail())) criteria.andEmailEqualTo(user.getEmail());
        if (!StringUtils.isEmpty(user.getTel())) criteria.andTelEqualTo(user.getTel());
        if (user.getDeptId() != null && user.getDeptId() > 0) criteria.andDeptIdEqualTo(user.getDeptId());
        if (user.getDutyId() != null && user.getDutyId() > 0) criteria.andDutyIdEqualTo(user.getDutyId());
        if (user.getDutyLevel() != null && user.getDutyLevel() > 0) criteria.andDutyLevelEqualTo(user.getDutyLevel());
        if (user.getRoleId() != null && user.getRoleId() > 0) criteria.andRoleIdEqualTo(user.getRoleId());
        return example;
    }*/

    /**
     * md5加密 用户密码明文
     * @param username 用户名
     * @param password 密码
     * @return md5值
     */
    public String toHex(String username, String password) {
        try {
            Md5Hash md5Hash = new Md5Hash(password, username, 101);
            return md5Hash.toHex();
        } catch (Exception e) {
            log.error("{}", e.getMessage());
            return "";
        }
    }
}
